/*
 Xern Entity Relocation Network
 Copyright (C) 2010-2011 Ronie Salgado <roniesalg@gmail.com>

 Permission is hereby granted, free of charge, to any person obtaining a copy
 of this software and associated documentation files (the "Software"), to deal
 in the Software without restriction, including without limitation the rights
 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 copies of the Software, and to permit persons to whom the Software is
 furnished to do so, subject to the following conditions:

 The above copyright notice and this permission notice shall be included in
 all copies or substantial portions of the Software.

 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 THE SOFTWARE.
*/

#include <string.h>
#include "Xern/StringTable.hpp"

namespace Xern
{
	StringTable::StringTable()
	{
	}

	StringTable::~StringTable()
	{
		// Delete each one of the strings.
		for(size_t i = 0; i < strings.size(); i++)
			delete strings[i];
	}

	u32 StringTable::AddString(const std::string &string)
	{
		// Check if we already have the string.
		StringIds::const_iterator it = stringIds.find(&string);
		if(it != stringIds.end())
			return it->second;

		// Create a string copy.
		std::string *newString = new std::string(string);

		// Store the string id.
		u32 ret = strings.size();

		// Add the string
		strings.push_back(newString);
		stringIds.insert(std::make_pair(newString, ret));

		// Return the string id.
		return ret;
	}

	std::string StringTable::GetString(u32 id)
	{
		if(id < strings.size())
			return *strings[id];
		return std::string();
	}

	bool StringTable::ReadStringTable(DataStream &in)
	{
		// Read the table header.
		FileStringTable table;
		in >> table.dataLen >> table.numRecords;

		// Read the table records.
		FileStringRecord *records = new FileStringRecord[table.numRecords];
		for(u32 i = 0; i < table.numRecords; i++)
		{
			in >> records[i].stringOffset;
			in >> records[i].stringLen;
		}

		// Read the table data.
		u8 *stringData = new u8[table.dataLen];
		in.Read(table.dataLen, stringData);

		// Parse the records.
		strings.reserve(table.numRecords);
		for(u32 i = 0; i < table.numRecords; i++)
		{
			FileStringRecord &r = records[i];
			std::string *newString = NULL;

			if(r.stringOffset + r.stringLen >= table.dataLen)
				newString = new std::string();
			else
			{
				u8 *start = stringData + r.stringOffset;
				u8 *end = stringData + r.stringOffset + r.stringLen;
				newString = new std::string(start, end);
			}

			strings.push_back(newString);
			stringIds.insert(std::make_pair(newString, i));
		}

		// Delete the data.
		delete [] records;
		delete [] stringData;

		return true;
	}

	bool StringTable::WriteStringTable(DataStream &out)
	{
		// Prepare the header
		FileStringTable table;
		table.dataLen = 0;
		table.numRecords = strings.size();

		// Calculate the data len.
		for(size_t i = 0; i < strings.size(); i++)
			table.dataLen += strings[i]->size() + 1;

		// Write the table header.
		out << table.dataLen << table.numRecords;

		// Create the data buffer.
		u8 *stringBuffer = new u8[table.dataLen];

		// Write the records.
		FileStringRecord record;
		u32 offset = 0;
		for(size_t i = 0; i < strings.size(); i++)
		{
			std::string *str = strings[i];

			// Fill the record and write it.
			record.stringOffset = offset;
			record.stringLen = str->size();
			out << record.stringOffset;
			out << record.stringLen;

			// Store the string into the string buffer.
			strcpy((char*)(stringBuffer + offset), str->c_str());

			// Increase the offset.
			offset += record.stringLen + 1;
		}

		// Write the string data.
		out.Write(table.dataLen, stringBuffer);

		// Delete the data buffer.
		delete [] stringBuffer;

		return true;
	}

}; // namespace Xern
